package com.lgd.juc.practice;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程轮流打印
 * 编写一个程序，开启 3 个线程，这三个线程的 ID 分别为 A、B、C，每个线程将自己的 ID 在屏幕上打印 10 遍，要求输出的结果必须按顺序显示。
 * 如：ABCABCABC…… 依次递归
 */
public class TurnPrint {

    private int num = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public static void main(String[] args) {
        TurnPrint tp = new TurnPrint();
        new Thread(() -> {
            while (true){
                tp.printA();
            }
        }, "t1").start();
        new Thread(() -> {
            while (true){
                tp.printB();
            }

        }, "t2").start();
        new Thread(() -> {
            while (true){
                tp.printC();
            }

        }, "t3").start();
    }

    public void printA() {
        lock.lock();
        try {
            if (num % 3 != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            num++;
            Thread.sleep(1000);
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            //1. 判断
            if (num % 3 != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            num++;
            Thread.sleep(1000);
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            if (num % 3 != 0) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            num++;
            Thread.sleep(1000);
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
